package com.example.test_01.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.test_01.R;
import com.example.test_01.model.User;
import com.example.test_01.service.UserService;
import com.example.test_01.service.UserServiceImpl;

import java.util.List;

public class UserAdapter extends RecyclerView.Adapter <UserAdapter.ViewHolder> {

    private List<User> userList;
    private final UserService userService = new UserServiceImpl();

    static class ViewHolder extends RecyclerView.ViewHolder{
        TextView Username;
        Button BtnDel;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            Username = itemView.findViewById(R.id.text_user_item_name);
            BtnDel = itemView.findViewById(R.id.btn_user_item_del);
        }
    }

    private void listUser(){
        userList = userService.list();
    }

    public UserAdapter() {
        listUser();
    }

    /**
     * @param parent
     * @param viewType
     * @return
     * @desc  用户点击删除事件
     */
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_item,parent,false);
        ViewHolder holder = new ViewHolder(view);
        holder.BtnDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int position = holder.getAdapterPosition();
                User user = userList.get(position);
                userService.delUserById(user.getId());

                // 删除后刷新显示
                userList = userService.list();
                notifyDataSetChanged();
            }
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        User user = userList.get(position);
        holder.Username.setText(user.getUsername());
    }

    @Override
    public int getItemCount() {
        return userList.size();
    }
}
